<template>
  <n-tag v-bind="$attrs" :color="dictItem.color">
    {{ dictItem.label || "/" }}
  </n-tag>
</template>
<script setup lang="ts">
import { onMounted, reactive, watch } from "vue";
import { DictStorage } from "@/storage/dict.storage";
import { IDictTagProps } from "./props";
import { isEmpty } from "lodash-es";

const props = defineProps<IDictTagProps>();
const dictItem = reactive({
  label: "",
  value: "",
  color: {
    color: "",
    textColor: "#f2f2f2",
  },
});

watch(
  () => [props.value, props.dict],
  ([newVal, newDict]) => {
    if (newVal && newDict) {
      const dictItemList = DictStorage.getDictItemsByCode(newDict);

      if (!isEmpty(dictItemList) && dictItemList.length) {
        const _targetDictItem =
          dictItemList.find((item: any) => item.value === newVal) || {};
        dictItem.label = _targetDictItem.label;
        dictItem.value = _targetDictItem.value;
        dictItem.color.color = _targetDictItem.color;
      }
    }
  }
);

const init = () => {
  if (props.dict) {
    const dictItemList = DictStorage.getDictItemsByCode(props.dict);

    if (!isEmpty(dictItemList) && dictItemList.length) {
      const _targetDictItem =
        dictItemList.find((item: any) => item.value === props.value) || {};
      dictItem.label = _targetDictItem.label;
      dictItem.value = _targetDictItem.value;
      dictItem.color.color = _targetDictItem.color;
    }
  }
};

onMounted(() => {
  init();
});
</script>
